<template>
  <div>
    <!-- <h1 class="mb-2">商家列表</h1> -->

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="100" class="mb-2">
        <el-col :span="8">
          <el-input placeholder="请输入商家账号" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="search">查询</el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加商家</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table
        :data="users"
        border
        stripe
        class="mb-2"
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column label="用户ID" prop="id" min-width="150"></el-table-column>
        <el-table-column label="用户名" prop="name" width="110"></el-table-column>
        <el-table-column label="密码" prop="pwd" min-width="150"></el-table-column>
        <el-table-column label="审核失败次数总数" prop="failed_total" width="90"></el-table-column>
        <el-table-column label="连续审核失败次数" prop="failed_series" width="90"></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.status ? '禁用' : '正常'" placement="top">
              <el-switch
                active-value="正常"
                inactive-value="禁用"
                :value="scope.row.status ? '禁用' : '正常'"
                @change="userStateChanged(scope.row)"
              ></el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetPwd(scope.row)">重置密码</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <Pagination :obj="obj" @pagination="getUserList($event)" />
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加商家" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item> -->
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";

export default {
  components: {
    Pagination,
  },
  data() {
    // 验证手机号的规则
    let checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

      if (reg.test(value)) {
        // 合法的手机号
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    // 密码安全性要求
    let validatePass = (rule, value, callback) => {
      // 6-16位, 数字, 字母, 字符至少包含两种, 同时不能包含中文和空格
      let reg = /(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{6,16}$/;
      if (!reg.test(value)) {
        callback(new Error("密码长度需6-16位，数字、字母、字符至少包含两种"));
      } else {
        callback();
      }
    };

    return {
      obj: {
        total: 0,
      },
      users: [],
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        id: "",
        username: "",
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserList();
    this.$store.commit("changeBreadcrumb", this.$route);
  },
  methods: {
    search() {
      let reg = /\S/g;
      // 若输入内容为空，禁止查询
      if (!reg.test(this.queryInfo.query)) return;
      this.getUserList();
    },
    async getUserList(page) {
      if (page && page.newPage) this.queryInfo.pagenum = page.newPage;
      if (page && page.newSize) this.queryInfo.pagesize = page.newSize;

      const formData = new FormData();
      formData.append("name", this.queryInfo.query);
      formData.append("page", this.queryInfo.pagenum);
      formData.append("rows", this.queryInfo.pagesize);
      formData.append("user_type", 1);
      const { data: res } = await this.$http.post("findByPage", formData);
      console.log(res, "账号信息");
      if (res.code != "0") return this.$message("获取商家列表失败");

      this.users = res.data.result;
      this.obj.total = res.data.totalCount;
    },
    // 监听 switch 开关状态的改变
    userStateChanged(row) {
      this.$confirm("确定改变用户状态？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let status = row.status == 0 ? 1 : 0;
          const formData = new FormData();
          formData.append("id", row.id);
          formData.append("status", status);
          const { data: res } = await this.$http.post("updateStatus", formData);
          if (res.code != "0") {
            return this.$message.error("改变用户状态失败！");
          }
          row.status = status;
          this.$message.success("改变用户状态成功");
          // 重新获取用户列表数据
          this.getUserList();
        })
        .catch(() => {
          this.$message("已取消修改！");
        });
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const formData = new FormData();
        formData.append("phone", this.addForm.username);
        const { data: res } = await this.$http.post("save", formData);
        // console.log(res);
        if (res.code != 0) {
          return this.$message.error("添加用户失败！");
        }
        this.$message.success("添加用户成功！");
        // 隐藏添加用户的对话框
        this.addDialogVisible = false;
        // 重新获取用户列表数据
        this.getUserList();
      });
    },
    // 重置用户密码
    resetPwd(row) {
      this.$confirm("确定重置用户密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const formData = new FormData();
          formData.append("name", row.name);
          const { data: res } = await this.$http.post("resetPwd", formData);
          if (res.code != "0") {
            return this.$message.error("重置用户密码失败！");
          }
          this.$message.success("重置用户密码成功");
          // 重新获取用户列表数据
          this.getUserList();
        })
        .catch(() => {
          this.$message("已取消重置！");
        });
    },
    // 根据id删除对应的用户信息
    async removeUserById(row) {
      //弹框询问用户是否删除数据
      const confirmResult = await this.$confirm("此操作将永久删除该用户 , 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      //console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      // console.log(row);
      const formData = new FormData();
      formData.append("id", row);
      const { data: res } = await this.$http.post("del", formData);
      // console.log(res);
      if (res.code != "0") {
        return this.$message.error("删除用户失败！");
      }
      this.$message.success("删除用户成功！");
      this.getUserList();
    },
  },
};
</script>

<style lang="scss"></style>
